package com.example.sens.service.impl;

import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.plugins.pagination.Pagination;
import com.example.sens.mapper.UserMapper;
import com.example.sens.entity.User;
import com.example.sens.service.UserService;

import com.example.sens.utils.ExportExcelUtils;
import com.example.sens.utils.Response;
import com.example.sens.vo.UserVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;

/**
 * <pre>
 *     用户业务逻辑实现类
 * </pre>
 *
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired(required = false)
    private UserMapper userMapper;

    @Override
    public void saveByUser(User user,HttpSession session) throws Exception{
        if (user != null && user.getUserId() != null) {
            userMapper.updateById(user);
        } else {
            if(!CollectionUtils.isEmpty(userMapper.checkStudentId(user.getStudentId()))) {
                throw new Exception("该学号已存在，请重新输入");
            }
            userMapper.insert(user);
        }
        session.removeAttribute("user");
        session.setAttribute("user", user);
    }

    @Override
    public User findByUserName(String userName) {
        User param = new User();
        param.setUserName(userName);
        param.setStudentId(userName);
        return userMapper.selectByNameAndSId(param);
    }

    @Override
    public User findByUserId(Long userId) {
        return userMapper.selectById(userId);
    }


    @Override
    public void removeUser(Long userId) {
        userMapper.deleteById(userId);
    }

    @Override
    public Page<User> findAll(Page<User> page) {
        return page.setRecords(userMapper.findAll(page));
    }

    @Override
    public Response<String> exportExcel(UserVo param) {
        param.setPageSize(0);
        List<User> users = userMapper.findAll(new Page(param.getPageNo(), param.getPageSize()));
        List<Object[]> dataList = new ArrayList<>();
        users.stream().forEach(a -> {
            Object[] objects  = {
                    dataList.indexOf(a) + 1,
                    a.getStudentId(),
                    StringUtils.isNotBlank(a.getUserName()) ? a.getUserName() : null,
                    a.getType().equals("user") ? "学生" : "老师",
            };
            dataList.add(objects);
        });
        String title = "学生信息表";
        String rowName[] = {"编号","学号","姓名","职位"};
        String layout[] = {"center", "center", "center", "center"};
        Response<String> response = ExportExcelUtils.excelPath(dataList, rowName, title, layout);
        response.setSuccess(true);
        return response;
    }

}
